package com.pan.admin.module.crm.service.impl;

import com.gitee.apanlh.util.base.CollUtils;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.base.IteratorUtils;
import com.gitee.apanlh.util.base.enums.Sort;
import com.gitee.apanlh.util.reflection.CopyUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.pan.admin.common.annotation.DataScope;
import com.pan.admin.common.core.domain.entity.SysUser;
import com.pan.admin.common.utils.DateUtils;
import com.pan.admin.common.utils.SecurityUtils;
import com.pan.admin.module.channel.entity.vo.ElementLabelVO;
import com.pan.admin.module.channel.entity.vo.ElementTreeVO;
import com.pan.admin.module.crm.dao.CrmDistributeLoanUserDao;
import com.pan.admin.module.crm.entity.CrmDistributeLoanUser;
import com.pan.admin.module.crm.entity.po.CrmLoanUserDistributeStatusPO;
import com.pan.admin.module.crm.entity.qo.CrmLoanUserDistributeStatusQO;
import com.pan.admin.module.crm.entity.vo.CrmAddVo;
import com.pan.admin.module.crm.entity.vo.CrmDeptVO;
import com.pan.admin.module.crm.entity.vo.CrmDistributeLoanUserVO;
import com.pan.admin.module.crm.entity.vo.TreeListVo;
import com.pan.admin.module.crm.service.CrmDistributeService;
import com.pan.admin.module.loanUser.dao.LoanUserRegisterTraceMapper;
import com.pan.admin.module.loanUser.entity.LoanUserRegister;
import com.pan.admin.module.loanUser.entity.po.LoanUserRegisterTracePO;
import com.pan.admin.module.loanUser.service.LoanUserRegisterService;
import com.pan.admin.module.system.dao.SysUserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * 甲方与用户关联Service业务层处理
 *
 * @author ts
 * @date 2023-11-13
 */

@Service
public class CrmDistributeLoanUserServiceImpl implements CrmDistributeService {

    @Autowired
    private CrmDistributeLoanUserDao crmDistributeLoanUserDao;
    @Autowired
    private SysUserDao userDao;

    @Autowired
    private LoanUserRegisterService loanUserRegisterService;
    @Autowired
    private LoanUserRegisterTraceMapper loanUserRegisterTraceMapper;

    /**
     * 根据ID获取列表甲方与用户关联
     *
     * @param id 甲方与用户关联主键
     * @return 甲方与用户关联
     */
    @Override
    public CrmDistributeLoanUser getById(Long id) {
        return crmDistributeLoanUserDao.getById(id);
    }

    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public CrmDistributeLoanUserVO getByLoanUserId(CrmDistributeLoanUserVO crmDistributeLoanUserVO) {
        Integer productId = SecurityUtils.getLoginUser().getUser().getProductId();
        crmDistributeLoanUserVO.setLoanProductId(productId);
        return crmDistributeLoanUserDao.getByLoanUserId(crmDistributeLoanUserVO);
    }

    /**
     * 查询甲方与用户关联列表
     *
     * @param crmLoanUser 甲方与用户关联
     * @return 甲方与用户关联
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<LoanUserRegister> list(CrmDistributeLoanUserVO crmLoanUser) {
        Integer productId = SecurityUtils.getLoginUser().getUser().getProductId();
        //  获取基本数据
        LoanUserRegister loanUserRegister = CopyUtils.copy(crmLoanUser, LoanUserRegister.class);
        loanUserRegister.setLoanProductId(productId.longValue());
        return loanUserRegisterService.listCrm(loanUserRegister);
    }

    /**
     * 新增甲方与用户关联
     * TODO 考虑数据越权
     *
     * @param crmAddVo 甲方与用户关联
     * @return 结果
     */
    @Override
    public int insertLoanJfUser(CrmAddVo crmAddVo) {
        //返回值变量
        int i = 0;
        //接收值判空
        if (ValidParam.isNotNull(crmAddVo)) {

            Integer userId = crmAddVo.getUserId();
            if (ValidParam.isNotNull(userId)) {
                //根据客服ID 获取客服全部信息
                SysUser sysUser = userDao.selectUserById(userId.longValue());

                List<Integer> loanUserIdList = crmAddVo.getLoanUserIdList();
                if (!ValidParam.isEmpty(loanUserIdList)) {
                    List<CrmDistributeLoanUser> userList = new ArrayList<>();

                    //遍历所选集合
                    for (Integer loanUserId : loanUserIdList) {
                        if (loanUserId != 0) {
                            CrmDistributeLoanUser crmLoanUser = new CrmDistributeLoanUser();
                            crmLoanUser.setLoanUserId(loanUserId);
                            crmLoanUser.setUserId(userId);
                            crmLoanUser.setDeptId(sysUser.getDeptId().intValue());
                            crmLoanUser.setLoanProductId(sysUser.getProductId());
                            int count = crmDistributeLoanUserDao.count(crmLoanUser);
                            crmLoanUser.setCreateTime(DateUtils.getNowDate());
                            if (count == 0) {
                                userList.add(crmLoanUser);
                            }
                        }
                    }

                    //插入节点数据
                    if (!ValidParam.isEmpty(userList)) {
                        i = crmDistributeLoanUserDao.batchInsert(userList);
                    }

                }

            }
        }

        return i;
    }

    /**
     * 修改甲方与用户关联
     *
     * @param crmLoanUser 甲方与用户关联
     * @return 结果
     */
//    @Override
//    public int updateLoanJfUser(CrmDistributeLoanUser crmLoanUser) {
//        return crmDistributeLoanUserDao.updateLoanJfUser(crmLoanUser);
//    }

    /**
     * 批量删除甲方与用户关联
     * TODO 考虑数据越权
     *
     * @param ids 需要删除的甲方与用户关联主键
     * @return 结果
     */
    @Override
    public int batchDeleteById(Long[] ids) {
        return crmDistributeLoanUserDao.batchDeleteById(ids);
    }

    /**
     * 左树树控数据
     *
     * @param crmLoanUser
     * @return
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public TreeListVo treeLeftList(CrmDistributeLoanUserVO crmLoanUser) {
        TreeListVo listVo = new TreeListVo();
        List<ElementTreeVO> treeVOList = new ArrayList<>();

        //  获取该改机构所有数据
        Integer productId = SecurityUtils.getLoginUser().getUser().getProductId();
        crmLoanUser.setLoanProductId(productId);
        List<CrmDeptVO> listCrmDeptVO = crmDistributeLoanUserDao.treeLeft(crmLoanUser);
        if (ValidParam.isEmpty(listCrmDeptVO)) {
            return listVo;
        }
        //  TODO 目前先固定写死
        //  37主体 38团队负责人 39员工
        CollUtils.filter(listCrmDeptVO, t -> !Eq.object(t.getRoleId(), 39L));

        //  父节点--子公司数据
        Map<Long, List<CrmDeptVO>> deptMap = CollUtils.groupByToLinked(listCrmDeptVO, t -> t.getDeptId());
        IteratorUtils.entrySet(deptMap, (deptId, listCrmUser) -> {
            //  部门节点
            CrmDeptVO dept = IteratorUtils.getFirst(listCrmUser);
            ElementTreeVO treeVO = new ElementTreeVO();
            treeVO.setLabel(dept.getDeptName());
            treeVO.setValue(dept.getDeptId());
            treeVO.setDisabled(true);

            //  子节点--客服用户数据
            List<ElementLabelVO> labelVOList = new ArrayList<>();
            IteratorUtils.array(listCrmUser, crmUser -> {
                ElementLabelVO elementLabelVO = new ElementLabelVO();
                elementLabelVO.setLabel("员工-账号[" + crmUser.getUserName() + "]-姓名[" + crmUser.getNickName() + "]");
                elementLabelVO.setValue(crmUser.getUserId());
                labelVOList.add(elementLabelVO);
            });
            treeVO.setList(labelVOList);
            treeVOList.add(treeVO);
        });
        listVo.setElementTreeVOList(treeVOList);
        return listVo;
    }


    /**
     * 树控数据  左树父节点点击渲染右树
     *
     * @param crmLoanUser
     * @return
     */
//    @Override
//    public TreeListVo treeList(CrmDistributeLoanUserVO crmLoanUser) {
//        Integer productId = SecurityUtils.getLoginUser().getUser().getProductId();
//        crmLoanUser.setLoanProductId(productId);
//        //最终返回数据 VO
//        TreeListVo listVo = new TreeListVo();
//        //整个树节点数据
//        List<ElementTreeVO> treeVOList = new ArrayList<>();
//        //默认选中的节点
//        List<Integer> crmDistributeLoanUsers = crmDistributeLoanUserDao.listByTree(crmLoanUser);
//        // 子公司数据 --父节点
//        List<CrmDeptVO> sysDeptList = crmDistributeLoanUserDao.listByTreeParent(crmLoanUser);
//        if (ValidParam.isEmpty(sysDeptList)) {
//            return listVo;
//        }
//
//        // 父节点 数据去重
//        List<CrmDeptVO> distinctResult = sysDeptList.stream()
//            .collect(Collectors.toMap(CrmDeptVO::getDeptId, item -> item, (existing, replacement) -> existing))
//            .values()
//            .stream()
//        .collect(Collectors.toList());
//
//        for (CrmDeptVO sysDept : distinctResult) {
//            //  父节点数据处理
//            ElementTreeVO treeVO = new ElementTreeVO();
//            treeVO.setLabel(sysDept.getDeptName());
//            treeVO.setValue(sysDept.getDeptId());
//            treeVO.setDisabled(true);
//            crmLoanUser.setDeptId(Math.toIntExact(sysDept.getDeptId()));
//
//            //  子节点数据
//            List<CrmDistributeLoanUserVO> crmDistributeLoanUserVOS = crmDistributeLoanUserDao.listByTreeChildren(crmLoanUser);
//            List<ElementLabelVO> labelVOList = new ArrayList<>();
//            if (!ValidParam.isEmpty(crmDistributeLoanUserVOS)) {
//                for (CrmDistributeLoanUserVO crmDistributeLoanUserVO : crmDistributeLoanUserVOS) {
//                    ElementLabelVO elementLabelVO = new ElementLabelVO();
//                    Integer loanUserId = crmDistributeLoanUserVO.getLoanUserId();
//                    if (ValidParam.isNotNull(loanUserId)) {
//                        //  子节点数据处理
//                        String phone = crmDistributeLoanUserVO.getPhone();
//                        String userName = crmDistributeLoanUserVO.getUserName();
//                        if (userName == null) {
//                            userName = "暂无";
//                        }
//                        String label = phone + "-" + userName;
//                        elementLabelVO.setLabel(label);
//                        elementLabelVO.setDisabled(true);
//                        elementLabelVO.setValue(loanUserId.longValue());
//                        labelVOList.add(elementLabelVO);
//                    }
//                }
//            }
//            treeVO.setList(labelVOList);
//            treeVOList.add(treeVO);
//        }
//        listVo.setDefaultIdList(crmDistributeLoanUsers);
//        listVo.setElementTreeVOList(treeVOList);
//
//        return listVo;
//    }

    /**
     * 左树节点渲染(子节点点击) 渲染右树
     *  TODO 考虑数据越权
     */
    @Override
    public TreeListVo treeListChildren(CrmDistributeLoanUserVO crmLoanUser) {
        Integer productId = SecurityUtils.getLoginUser().getUser().getProductId();
        crmLoanUser.setLoanProductId(productId);
        //  最终数据返回 VO
        TreeListVo listVo = new TreeListVo();
        //  整个树的节点数据
        List<ElementTreeVO> treeVOList = new ArrayList<>();
        List<ElementLabelVO> listLabel = new ArrayList<>();

        //  TODO 考虑数据权限
        // 客服用户数据 -- 父节点数据
        CrmDeptVO crmDeptVO = crmDistributeLoanUserDao.listByTreeParentRight(crmLoanUser);
        if (ValidParam.isNull(crmDeptVO)) {
            return listVo;
        }

        ElementTreeVO treeVO = new ElementTreeVO();
        treeVO.setLabel("当前选择账号[" + crmDeptVO.getUserName() + "]-姓名[" + crmDeptVO.getNickName() + "]");
        treeVO.setValue(0L);

        //  TODO 考虑数据权限
        //  获取该部门下获取全部用户数据 -- 子节点数据
        crmLoanUser.setDeptId(Math.toIntExact(crmDeptVO.getDeptId()));
        List<CrmDistributeLoanUserVO> listCrmAllUser = crmDistributeLoanUserDao.listByTreeChildren(crmLoanUser);
        if (ValidParam.isEmpty(listCrmAllUser)) {
            return listVo;
        }

        //  TODO 考虑数据权限
        //  获取客服用户已被分配的数据-默认选中的节点
        List<Integer> listCrmUserExistLoanUserId = crmDistributeLoanUserDao.listByTree(crmLoanUser);

        //  子节点数据处理
        IteratorUtils.array(listCrmAllUser, crmUser -> {
            ElementLabelVO elementLabelVO = new ElementLabelVO();
            Integer loanUserId = crmUser.getLoanUserId();

            //  客户手机号
            String phone = crmUser.getPhone();
            String userName = crmUser.getUserName();
            //  处理label 命名 手机号—用户名
            if (userName == null) {
                userName = "暂无";
            }
            String label = phone + "-" + userName;
            elementLabelVO.setValue(loanUserId.longValue());

            //  判断是否存在
            Integer checkLoanUserId = CollUtils.findOne(listCrmUserExistLoanUserId, crmUserExist -> Eq.object(loanUserId, crmUserExist));
            if (ValidParam.isNull(checkLoanUserId)) {
                elementLabelVO.setLabel("客户-" + label + "-[未分配]");
            } else {
                elementLabelVO.setDisabled(true);
                elementLabelVO.setDisabledSort(1);
                elementLabelVO.setLabel("客户-" + label + "-[已分配]");
            }
            listLabel.add(elementLabelVO);
        });

        //  排序已分配的放后面
        CollUtils.sort(listLabel, t -> t.getDisabledSort(), Sort.ASC);

        listVo.setDefaultIdList(listCrmUserExistLoanUserId);
        treeVO.setList(listLabel);
        treeVOList.add(treeVO);
        listVo.setElementTreeVOList(treeVOList);
        return listVo;
    }

    @Override
    @Transactional(readOnly = true)
    public List<CrmLoanUserDistributeStatusPO> listUserDistributeStatus(CrmLoanUserDistributeStatusQO crmLoanUserDistributeStatusQO) {
        return crmDistributeLoanUserDao.listUserDistributeStatus(crmLoanUserDistributeStatusQO);
    }

    /**
     * 删除甲方与用户关联信息
     *
     * @param id 甲方与用户关联主键
     * @return 结果
     */
    @Override
    public int deleteById(Long id) {
        return crmDistributeLoanUserDao.deleteById(id);
    }

    /**
     * 修改用户跟踪
     */
    @Override
    public int updateLoanUserRegisterTrace(LoanUserRegisterTracePO loanUserRegisterTracePO) {
        loanUserRegisterTracePO.setUpdateBy(SecurityUtils.getUsername());
        loanUserRegisterTracePO.setUpdateTime(DateUtils.getNowDate());
        return this.loanUserRegisterTraceMapper.replaceInto(loanUserRegisterTracePO);
    }

}
